package com.open.api.schedule;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.open.api.bo.MessageBO;
import com.open.api.config.property.FileProperty;
import com.open.api.config.property.FromSqlProperty;
import com.open.api.config.property.FtpProperty;
import com.open.api.ftp.common.ResponseData;
import com.open.api.ftp.common.TypeEnum;
import com.open.api.ftp.util.FileIOUtil;
import com.open.api.ftp.util.FtpUtil;
import com.open.api.mapper.SendinfoDao;
import com.open.api.mapper.SysSendDao;
import com.open.api.model.ResultModel;
import com.open.api.pojo.Sendinfo;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@Component
@EnableScheduling
@Async
public class AlarmTask {

    @Resource
    private SendinfoDao sendinfoDao;

    @Autowired
    private FileProperty fileProperty;

    @Autowired
    private FromSqlProperty fromSqlProperty;

    @Autowired
    private FtpUtil ftpUtil;
    
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private SysSendDao sysSendDao;
    
    @Autowired
    private FtpProperty ftpProperty;

    /**
     * 单向边界内网前置机读取内网数据发向外网
     * @throws InterruptedException
     */
    @Scheduled(cron = "0/30 * * * * *")
    public void run() throws InterruptedException {
        if(fromSqlProperty.getNeidaowai()){
            System.out.println(Thread.currentThread().getName()+"=====>>>>>使用cron  {}"+(System.currentTimeMillis()/1000));
            List<Sendinfo> sendinfoList= sendinfoDao.queryAll("N");
            if(sendinfoList!=null && sendinfoList.size()>0){
                for(int i=0;i<sendinfoList.size();i++){
                    Sendinfo sendinfo=sendinfoList.get(i);

                    JSONObject jsonObject=JSON.parseObject(sendinfo.getSendinfo());
                    MessageBO messageBO=JSON.toJavaObject(jsonObject,MessageBO.class);
                    ResultModel resultModel=new ResultModel();
                    FileIOUtil fileIOUtil=new FileIOUtil();
                    ResultModel resultModel_saveFile=fileIOUtil.saveDataToFile(messageBO,fileProperty.getUploaddir(),fileProperty.getSuffix());
                    String newFileName="";

                    if(resultModel_saveFile.isSuccess()){
                        newFileName= (String) resultModel_saveFile.getData();
                        FtpUtil ftpUtil=new FtpUtil();
                        String localTmpSendPath=fileProperty.getUploaddir()+messageBO.getSystem()+"/"+newFileName;
                        ResponseData responseData =ftpUtil.defaultUpload(ftpProperty.getHost(),ftpProperty.getPort(),ftpProperty.getUsername(),ftpProperty.getPassword(),ftpProperty.getBasepath(),ftpProperty.getPhysicalpath(),newFileName,new File(localTmpSendPath));
                        System.out.println(responseData.toString());
                        if(responseData.getCode()==0){
                            System.out.println("上传ftp成功");
                            ResponseData responseData_delFile=fileIOUtil.deleteFromServer(localTmpSendPath, TypeEnum.DELETETYPE_RMFILE.getCode());
                            if(responseData_delFile.getCode()==0){
                                resultModel.setSuccess(true);
                                Sendinfo sendinfo1=new Sendinfo();
                                sendinfo1.setId(sendinfo.getId());
                                sendinfo1.setStatus("Y");
                                sendinfo1.setReadtime(new Date());
                                int s =sendinfoDao.updateByPrimaryKeySelective(sendinfo1);
                                if(s>0){
                                    System.out.println("数据推送成功!");
                                }else{
                                    System.out.println("数据推送失败!");
                                }
                            }else{
                                resultModel.setSuccess(false);
                                resultModel.setErrorCode(String.valueOf(responseData_delFile.getCode()));
                                resultModel.setErrorMsg(resultModel_saveFile.getErrorMsg());
                                System.out.println(resultModel);
                            }
                        }else {
                            resultModel.setSuccess(false);
                            resultModel.setErrorCode(String.valueOf(responseData.getCode()));
                            resultModel.setErrorMsg(responseData.getMsg());
                            System.out.println(resultModel);
                        }
                    }else{
                        System.out.println(resultModel_saveFile.toString());
                    }

                }
            }
        }
    }

    /**
     * 单向边界内网前置机获取外网数据向内网应用发送数据
     */
    @Scheduled(cron = "0/30 * * * * *")
    public void sendInfoForUrl(){
        if(fromSqlProperty.getWaidaonei()){
            System.out.println("-----run start------");
            FTPClient ftpClient = null;
            JSONObject resResult = null;
            try {
                ResponseData connect_resp =ftpUtil.connect(ftpProperty.getHost(),ftpProperty.getPort(), ftpProperty.getUsername(), ftpProperty.getPassword());
                if(connect_resp.getCode()!=0){
                    System.out.println("连接 ftp 失败！");
                }else{
                    ftpClient= (FTPClient) connect_resp.getData();
                    if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {//是否连接成功,成功true,失败false
                        List<FTPFile> list = ftpUtil.listFiles(ftpClient,ftpProperty.getPhysicalpath()); //列出文件
                        list.sort(Comparator.comparing(FTPFile::getName));
                        for (FTPFile file : list) {

                            //ftpClient = ftpUtil.connect(ftpProperty.getHost(), ftpProperty.getPort(), ftpProperty.getUsername(), ftpProperty.getPassword());
                            InputStream inputStream = null;
                            BufferedReader bufferedReader = null;
                            String remotePath =ftpProperty.getPhysicalpath() + file.getName();
                            System.out.println("-----------------" + remotePath);

                            if (!file.getName().contains(".json")) {
                                continue;
                            }
                            try {
                                inputStream = ftpClient.retrieveFileStream(remotePath);
                                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                                StringBuffer strBuf = new StringBuffer();
                                String temp = "";
                                while ((temp = bufferedReader.readLine()) != null) {
                                    strBuf.append(temp);
                                }
                                JSONObject jsonObject = JSONObject.parseObject(strBuf.toString());
                                List<String> stringValue = Collections.singletonList(jsonObject.toJSONString());
                                List<MessageBO> messageBOS = stringValue.stream()
                                        .map(e -> JSON.parseObject(e, MessageBO.class)).collect(
                                                Collectors.toList());
                                System.out.println("--------------------messageBOS="+ messageBOS.toString());
                                for (MessageBO e : messageBOS) {
                                    resResult = send(e);
                                }
                                System.out.println("--发送完毕--");
                                if (resResult != null && resResult.getString("code").equals("0")) {
                                    System.out.println("--start delete");
                                    ftpUtil.deleteFile(ftpClient,ftpProperty.getPhysicalpath() + file.getName());
                                    System.out.println("--end delete");
                                }
                            } catch (Exception e) {
                                System.out.println(e.getMessage());
                            } finally {
                                try {
                                    if (bufferedReader != null) {
                                        bufferedReader.close();//关闭流
                                    }
                                    if(inputStream!=null) {
                                        inputStream.close();
                                    }
                                } catch (Exception e) {
                                    System.out.println("Close BufferedReader error:"+ e);
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                if (ftpClient != null) {
                    try {
                        ftpUtil.disconnect(ftpClient);
                    } catch (IOException e) {
                        System.out.println("channel getSession error:"+ e);
                    }
                }
            }

            System.out.println("-----run end------");
        }

    }

    public JSONObject send(MessageBO vo) {
        String o = JSONObject.toJSONString(vo);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> httpEntity = new HttpEntity<>(o, httpHeaders);
        System.out.println("--sendStart--");
        System.out.println("data="+o);
        String res = restTemplate.postForEntity(Objects.requireNonNull(sendUrl(vo.getSystem())), httpEntity, String.class).getBody();
        System.out.println("afterSendResult=="+res);
        System.out.println("--sendEnd--");
        return (JSONObject) JSONObject.parse(res);
    }

    private String sendUrl(String system) {
         String sendUrl =sysSendDao.getSendUrl(system);
        System.out.println("--sendUrl="+sendUrl);
            if (sendUrl == null) {
                return null;
            }
            return sendUrl;
    }
}
